package com.ibeeking.gmc.global.g.rest.service.impl;

import com.ibeeking.gmc.global.g.rest.service.IGroupService;
import com.ibeeking.found.common.enums.PublishStatusEnum;
import com.ibeeking.gmc.global.service.common.dos.GroupDO;
import com.ibeeking.gmc.global.service.common.dos.TenantDO;
import com.ibeeking.gmc.global.service.common.param.GroupParam;
import com.ibeeking.gmc.global.service.common.query.GroupPageQuery;
import com.ibeeking.gmc.global.service.common.query.GroupQuery;
import com.ibeeking.gmc.global.service.common.vo.GroupPageVO;
import com.ibeeking.gmc.global.service.common.vo.GroupVO;
import com.ibeeking.gmc.global.service.mapper.GroupMapper;
import com.ibeeking.gmc.global.service.mapper.TenantMapper;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements IGroupService {

    @Resource
    private TenantMapper tenantMapper;

    @Resource
    private GroupMapper groupMapper;


    /**
     * 添加集团
     *
     * @param groupParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(GroupParam groupParam) {
        //名称、代码验证
        this.checkGroup(groupParam);
        GroupDO groupDO = BeanUtil.convertBean(groupParam, GroupDO.class);
        groupDO.setPublishStatus(PublishStatusEnum.DISABLE.getValue());
        groupDO.setCreateTime(LocalDateTime.now());
        groupDO.setModifyTime(LocalDateTime.now());
        return this.groupMapper.insert(groupDO) > 0;
    }


    /**
     * 修改集团信息
     *
     * @param groupParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean modify(GroupParam groupParam) {
        //名称、代码验证
        this.checkGroup(groupParam);
        GroupDO groupDO = BeanUtil.convertBean(groupParam, GroupDO.class);
        groupDO.setPublishStatus(PublishStatusEnum.DISABLE.getValue());
        groupDO.setModifyTime(LocalDateTime.now());
        return this.groupMapper.updateById(groupDO) > 0;
    }


    /**
     * 根据id修改发布状态
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean changeStatus(Long id, Integer status, Long modifyBy) {
        GroupDO groupDO = new GroupDO();
        groupDO.setPublishStatus(status)
                .setModifyBy(modifyBy)
                .setModifyTime(LocalDateTime.now())
                .setId(id);
        return this.groupMapper.updateById(groupDO) > 0;
    }


    /**
     * 根据id删除集团
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean del(Long id) {

        //查询当前集团是否存在租户
        QueryWrapper<TenantDO> tenantQuery = new QueryWrapper<>();
        tenantQuery.lambda().eq(TenantDO::getParentId, id);
        List<TenantDO> tenantDOList = this.tenantMapper.selectList(tenantQuery);
        if (Collections3.isNotEmpty(tenantDOList)) {
            throw new BusinessException("当前集团下还有租户，不能删除");
        }
        //已经不存在租户
        return this.groupMapper.deleteById(id) > 0;
    }

    /**
     * 分页条件查询
     *
     * @param groupPageQuery
     * @return
     */
    @Override
    public Page<GroupPageVO> pageList(GroupPageQuery groupPageQuery) {
        Page<GroupDO> page = new Page<>(groupPageQuery.getPageNum(), groupPageQuery.getPageSize());

        QueryWrapper<GroupDO> queryWrapper = new QueryWrapper<>();
        //集团代码
        queryWrapper.lambda().like(StringUtils.isNotBlank(groupPageQuery.getCode()), GroupDO::getCode, groupPageQuery.getCode());
        //集团名称
        queryWrapper.lambda().like(StringUtils.isNotBlank(groupPageQuery.getName()), GroupDO::getName, groupPageQuery.getName());
        //集团联系人
        queryWrapper.lambda().like(StringUtils.isNotBlank(groupPageQuery.getContacts()), GroupDO::getContacts, groupPageQuery.getContacts());
        //集团联系电话
        String phone = groupPageQuery.getPhone();
        if (StringUtils.isNotBlank(phone)) {
            if (phone.length() > 5) {
                queryWrapper.lambda().likeRight(GroupDO::getPhone, phone);
            } else {
                throw new BusinessException("联系电话需要满6位才能查询");
            }
        }
        //集团地址
        queryWrapper.lambda().like(StringUtils.isNotBlank(groupPageQuery.getAddress()), GroupDO::getAddress, groupPageQuery.getAddress());
        //是否发布
        queryWrapper.lambda().eq(groupPageQuery.getPublishStatus()!=null,GroupDO::getPublishStatus,groupPageQuery.getPublishStatus());
        //根据创建时间 最新的在最前面
        queryWrapper.lambda().orderByDesc(GroupDO::getCreateTime);

        return BeanUtil.convertPage(this.groupMapper.selectPage(page, queryWrapper), GroupPageVO.class);
    }

    /**
     * 根据id查看详情
     *
     * @param id
     * @return
     */
    @Override
    public GroupVO view(Long id) {
        GroupDO groupDO = this.groupMapper.selectById(id);
        GroupVO groupVO = BeanUtil.convertBean(groupDO, GroupVO.class);
        return groupVO;
    }

    @Override
    public List<GroupVO> list(GroupQuery groupQuery){
        QueryWrapper<GroupDO> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(GroupDO::getPublishStatus,PublishStatusEnum.ENABLE.getValue());
        List<GroupDO> groupDOS = this.groupMapper.selectList(queryWrapper);
        return JsonUtils.jsonToList(groupDOS,GroupVO.class);
    }


    /**
     * 检查集团名称、集团代码是否有重复
     *
     * @param groupParam
     */
    private void checkGroup(GroupParam groupParam) {

        if (groupParam.getPhone().length() < 6) {
            throw new BusinessException("集团联系电话至少要保留8位");
        }

        QueryWrapper<GroupDO> quary = new QueryWrapper<>();

        //检查集团名称
        quary.lambda().eq(GroupDO::getName, groupParam.getName())
                .ne(groupParam.getId() != null, GroupDO::getId, groupParam.getId());
        List<GroupDO> groupList = this.groupMapper.selectList(quary);
        if (Collections3.isNotEmpty(groupList)) {
            throw new BusinessException("集团名称不能重复");
        }

        quary.clear();

        //检查集团代码
        quary.lambda().eq(GroupDO::getCode, groupParam.getCode())
                .ne(groupParam.getId() != null, GroupDO::getId, groupParam.getId());
        groupList = this.groupMapper.selectList(quary);
        if (Collections3.isNotEmpty(groupList)) {
            throw new BusinessException("集团代码不能重复");
        }
    }


}
